package one.stand.controller;

import com.github.pagehelper.PageHelper;
import com.jmp.api.admin.dto.*;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.feign.TicketFeign;
import com.jmp.service.api.admin.dto.TicketOrderMemoDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.dto.Company2Dto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageResponse2;
import one.stand.dto.UserDto;
import one.stand.mapper.CompanyApiAdminMapper;
import one.stand.model.BusinessCard;
import one.stand.model.ResultModel;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.CompanyBaseService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.DownLoadExcelUtil;
import one.stand.util.SqlUtil;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author cjr
 */
@Api("奖券订单")
@RestController
@RequestMapping("adminApi/ticket/order")
public class TicketOrderController {
    @Autowired
    private TicketFeign ticketFeign;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;

    @Autowired
    private CompanyApiAdminMapper companyApiAdminMapper;

    @ApiOperation("列表")
    @GetMapping("")
    @SecurityAuthCheck
    public ResultModel<TicketOrderListResponse> list(TicketOrderListRequest request) {

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<TicketOrderListResponse.Order> orders = companyApiAdminMapper.selectTicketOrderList(SqlUtil.like(request.getKeyword()), request.getStatus()
                , SqlUtil.like(request.getOrderNo()), SqlUtil.likeLeft(request.getOrderNoEnd()), request.getType());
        PageResponse2<TicketOrderListResponse.Order> orderPageResponse2 = ConvertUtils.page2(orders, ticket -> {
            UserDto user = userAdminService.get(ticket.getCreater());
            ticket.setCreaterName(user.getName());
            if (StringUtils.isBlank(ticket.getPhone())) {
                ticket.setPhone(user.getPhone());
            }
            ticket.setAuditorName(userAdminService.get(ticket.getAuditor()).getName());
            ticket.setCompanyType(BooleanUtils.toInteger(companyBaseService.isByLabel(ticket.getCompanyId(), CompanyBaseService.LABEL_SUPPLIER)));
            return ticket;
        });
        TicketOrderListResponse response = TicketOrderListResponse.builder()
                .orders(orderPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("审核-通过")
    @PostMapping("audit/pass")
    @SecurityAuthCheck
    public ResultModel auditPass(@RequestBody TicketOrderAuditPassRequest request) {

        ResultModel resultModel = ticketFeign.orderPass(com.jmp.service.api.admin.dto.TicketOrderPassRequest.builder()
                .id(request.getId())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation("审核-拒绝")
    @PostMapping("audit/refuse")
    @SecurityAuthCheck
    public ResultModel auditRefuse(@RequestBody TicketOrderAuditPassRequest request) {

        ResultModel resultModel = ticketFeign.orderRefuse(com.jmp.service.api.admin.dto.TicketOrderPassRequest.builder()
                .id(request.getId())
                .memo(request.getMemo())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation("备注")
    @PostMapping("memo")
    @SecurityAuthCheck
    public ResultModel memo(@RequestBody TicketOrderAuditPassRequest request) {

        ResultModel resultModel = ticketFeign.orderMemo(TicketOrderMemoDto.builder()
                .id(request.getId())
                .memoTel(request.getMemo())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation("订单统计")
    @GetMapping("company")
    @SecurityAuthCheck
    public ResultModel<TicketOrderCompanyResponse> company(TicketOrderCompanyRequest request) {

        TicketOrderCompanyResponse.Count count = companyApiAdminMapper.selectTicketOrderCount(SqlUtil.like(request.getKeyword()));

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<TicketOrderCompanyResponse.Company> orders = companyApiAdminMapper.selectTicketCompanyList(SqlUtil.like(request.getKeyword()));
        PageResponse2<TicketOrderCompanyResponse.Company> orderPageResponse2 = ConvertUtils.page2(orders, ticket -> ticket);
        TicketOrderCompanyResponse response = TicketOrderCompanyResponse.builder()
                .count(count)
                .companies(orderPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("订单统计-导出")
    @GetMapping("company/download")
    @SecurityAuthCheck
    public void companyDownload(TicketOrderCompanyRequest request, HttpServletResponse response) throws IOException {

        List<TicketOrderCompanyResponse.Company> data = companyApiAdminMapper.selectTicketCompanyList(SqlUtil.like(request.getKeyword()));
        DownLoadExcelUtil.download(response, "订单统计", "企业列表", TicketOrderCompanyResponse.Company.class, data);
    }

    @ApiOperation("订单统计-明细")
    @GetMapping("company/detail")
    @SecurityAuthCheck
    public ResultModel<TicketOrderCompanyDetailResponse> companyDetail(TicketOrderCompanyDetailRequest request) {

        Company2Dto company = companyBaseService.get2(request.getCompanyId());
        BusinessCard businessCard = businessCardBaseService.getByUserId(company.getUserId());

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<TicketOrderCompanyDetailResponse.Order> orders = companyApiAdminMapper.selectTicketCompanyDetailList(request.getCompanyId(), request.getStatus());
        PageResponse2<TicketOrderCompanyDetailResponse.Order> orderPageResponse2 = ConvertUtils.page2(orders, ticket -> {
            if (StringUtils.isNoneBlank(ticket.getAuditor())) {
                ticket.setAuditor(userAdminService.get(Integer.valueOf(ticket.getAuditor())).getName());
            }
            ticket.setCreaterName(userAdminService.get(ticket.getCreater()).getName());
            return ticket;
        });
        TicketOrderCompanyDetailResponse response = TicketOrderCompanyDetailResponse.builder()
                .companyName(company.getCompanyName())
                .companyUser(StringUtils.isNoneBlank(company.getUserName()) ? company.getUserName() : businessCard.getName())
                .companyTel(StringUtils.isNoneBlank(company.getPhone()) ? company.getPhone() : businessCard.getPhone())
                .addr(company.countAddress())
                .orders(orderPageResponse2)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation("订单统计-明细-导出")
    @GetMapping("company/detail/download")
    @SecurityAuthCheck
    public void companyDetailDownload(TicketOrderCompanyDetailRequest request, HttpServletResponse response) throws IOException {

        List<TicketOrderCompanyDetailResponse.Order> orders = companyApiAdminMapper.selectTicketCompanyDetailList(request.getCompanyId(), request.getStatus());
        List<TicketOrderCompanyDetailDownloadResponse> data = ConvertUtils.list(orders, order -> {
            if (StringUtils.isNoneBlank(order.getAuditor())) {
                order.setAuditor(userAdminService.get(Integer.valueOf(order.getAuditor())).getName());
            }
            return TicketOrderCompanyDetailDownloadResponse.builder()
                    .orderNo(order.getOrderNo())
                    .orderMoney(order.getOrderMoney())
                    .companyName(order.getCompanyName())
                    .createrName(userAdminService.get(order.getCreater()).getName())
                    .ctime(order.getCtime())
                    .auditor(order.getAuditor())
                    .status(order.getStatus() == 1 ? "已通过" : (order.getStatus() == 2 ? "未通过" : "审核中"))
                    .memo(StringUtils.defaultIfBlank(order.getMemo(), StringUtils.EMPTY))
                    .build();
        });
        DownLoadExcelUtil.download(response, "订单统计-明细", "订单", TicketOrderCompanyDetailDownloadResponse.class, data);
    }
}
